/*
 * COPYRIGHT. ShenZhen JiMi Technology Co., Ltd. 2017.
 * ALL RIGHTS RESERVED.
 *
 * No part of this publication may be reproduced, stored in a retrieval system, or transmitted,
 * on any form or by any means, electronic, mechanical, photocopying, recording, 
 * or otherwise, without the prior written permission of ShenZhen JiMi Network Technology Co., Ltd.
 *
 * Amendment History:
 * 
 * Date                   By              Description
 * -------------------    -----------     -------------------------------------------
 * 2017年8月10日    li.shangzhi         Create the class
 * http://www.jimilab.com/
 */

package com.jimi.gateway.web;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.web.AbstractErrorController;
import org.springframework.boot.autoconfigure.web.ErrorAttributes;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jimi.commons.DatetimeUtil;

/**
 * @FileName ControllerExceptionHandler.java
 * @Description:
 *
 * @Date 2017年8月10日 上午11:17:24
 * @author li.shangzhi
 * @version 1.0
 */
@Order(Ordered.HIGHEST_PRECEDENCE)
@ControllerAdvice
@Controller
@RequestMapping("${server.error.path:${error.path:/error}}")
public class ControllerExceptionHandler extends AbstractErrorController {

	private static final Logger log = LoggerFactory.getLogger(ControllerExceptionHandler.class);

	@Value("${server.error.path:${error.path:/error}}")
	private static String errorPath = "/error";

	public ControllerExceptionHandler(ErrorAttributes errorAttributes) {
		super(errorAttributes);
	}

	@RequestMapping
	@ResponseBody
	public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
		Map<String, Object> body = getErrorAttributes(request, false);
		log.error("发生错误：{}", body.toString());
		HttpStatus status = getStatus(request);
		body.clear(); // 清除系统默认返回，构造自定义返回
		body.put("code", status.value());
		body.put("message", status.getReasonPhrase());
		body.put("timestamp", DatetimeUtil.getCurrentDate());
		return new ResponseEntity<>(body, status);
	}

	@Override
	public String getErrorPath() {
		return errorPath;
	}

}
